package com.example.deterwrw.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;


/**
 *  信号量demo 模拟20个核心线程池，但是只希望只有2个并发情况
 */
@RestController
public class SemaphoreDemoController {
  public static final ExecutorService executorService = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    final Semaphore semaphore =new Semaphore(2, true);
    @GetMapping("/tst22212311")
    public String tst22212311() throws Exception {
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            submitTask(new Runnable(){
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("执行任务：" + finalI + "线程"+Thread.currentThread().getName());
                }
            });
        }
        return "";
    }

    public void submitTask(Runnable task) {
        // 提交任务到线程池之前先获取信号量许可
        try {
            semaphore.acquire(); // 这里会阻塞直到获得一个许可
            executorService.submit(() -> {
                try {
                    task.run();
                } finally {
                    // 任务完成后释放信号量许可
                    semaphore.release(); // 释放许可，允许其他等待的任务开始
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 设置中断状态
            // 处理异常...
        }
    }

}
